﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using MLY.Reports.AdvancedReports;
using MLY.Dal;

namespace MLY.Bll
{

  [DataObject]
  public class clsOrganization
  {

    #region Constructors
    // ==================================
    public clsOrganization()
    {
      _db = new Dal.lqKbmDataContext();
      _DataRow = new Dal.TableOrganization();
      IsExist = false;
    }

    public clsOrganization(int Id)
    {
      _db = new Dal.lqKbmDataContext();
      _DataRow = (from o in _db.TableOrganizations
                  where (o.OrganizationId == Id)
                  select o).FirstOrDefault();
      if (_DataRow != null)
      {
        IsExist = true;
      }
      else
      {
        _DataRow = new MLY.Dal.TableOrganization();
        IsExist = false;
      }
    }

    // OLD code with bugs. do not understand why org_id and not user_id, why string and not int.
    //public clsOrganization(string in_orgId)
    //{
    //  int orgId = int.Parse(in_orgId);
    //  _db = new Dal.lqKbmDataContext();
    //  _DataRow = (from o in _db.TableOrganizations
    //              join p in _db.TableUsers
    //              on o.OrganizationId equals p.OrganiztionId
    //              select o).FirstOrDefault();

    //  IsExist = true;
    //}


    // ==================================
    #endregion

    #region Static Members
    // ==================================.

    public static List<Dal.TableOrganization> GetClients()
    {
      using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
      {

        return (from o in db.TableOrganizations
                where (o.IsClient != null) && (bool)o.IsClient
                select o).ToList<Dal.TableOrganization>();

      }
    }

    public static List<Dal.TableOrganization> GetAllOrganizations()
    {
      using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
      {
        return (from p in db.TableOrganizations select p).ToList();

      }
    }

    public static List<Dal.TableOrganization> GetOrganizationsPlusSelect()
    {
      using (lqKbmDataContext db = new lqKbmDataContext())
      {
        List<TableOrganization> list = new List<TableOrganization>();
        TableOrganization organization = new TableOrganization();
        organization.OrganizationId = 0;
        organization.OrganizationName = "<Select Organiztion>";
        list.Add(organization);
        list.AddRange((from org in db.TableOrganizations select org).ToList<TableOrganization>());
        return list;
      }
    }

    public static List<Dal.TableOrganization> GetContractors()
    {
      using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
      {
        return (from o in db.TableOrganizations where o.IsContractor == true select o).ToList<Dal.TableOrganization>();
      }
    }
    public static List<Dal.TableOrganization> GetContractors(string prefix)
    {
      using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
      {
        return (from o in db.TableOrganizations where o.IsContractor == true && o.OrganizationName.Contains(prefix) select o).ToList<Dal.TableOrganization>();
      }
    }

    public static Dictionary<Dal.TableOrganization, int> GetContractorsForSearch(string prefix, int classificationId, string Tag)
    {
      if (prefix == null)
        prefix = "";

      using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
      {
        Dictionary<Dal.TableOrganization, int> retVal = new Dictionary<MLY.Dal.TableOrganization, int>();

        List<Dal.TableOrganization> ContractorsList = (from o in db.TableOrganizations
                                                       join p in db.TableOrganizationClassifications on o.OrganizationId equals p.OrganizationId
                                                       where o.OrganizationName.Contains(prefix) &&
                                                       ((p.ClassificationId == classificationId) || (classificationId == 0)) &&
                                                       (o.Tag.Contains(Tag) || Tag == "%")
                                                       select o).ToList<Dal.TableOrganization>().ToList();
        //Dictionary<int, int> rates = new Dictionary<int, int>();
        //foreach (Dal.TableOrganization Contractor in ContractorsList)
        //{
        //    if (!rates.Keys.Contains(Contractor.OrganizationId))
        //    {
        //        int cnt = db.TableOrganizationRelations.Where(S => S.CustomerId == Contractor.OrganizationId || S.ContractorId == Contractor.OrganizationId).Count();
        //        rates.Add(Contractor.OrganizationId, cnt);
        //    }
        //}
        //rates = RateContractors(rates);

        foreach (Dal.TableOrganization Contractor in ContractorsList)
        {
          if (!retVal.Keys.Contains(Contractor))//&& rates.ContainsKey(Contractor.OrganizationId))
          {
            int cnt = db.TableOrganizationRelations.Where(S => S.CustomerId == Contractor.OrganizationId || S.ContractorId == Contractor.OrganizationId).Count();
            retVal.Add(Contractor, cnt);
            //retVal.Add(Contractor,rates[Contractor.OrganizationId]);
          }
        }
        var items = from k in retVal.Keys
                    orderby retVal[k] descending
                    select k;

        Dictionary<Dal.TableOrganization, int> SortedretVal = new Dictionary<MLY.Dal.TableOrganization, int>();

        foreach (Dal.TableOrganization k in items)
        {
          SortedretVal.Add(k, retVal[k]);
        }
        return SortedretVal;

      }
    }

    private class ContructorMonth
    {
      int ContructorId { get; set; }
      string MonthId { get; set; }

    }
    public static Reports.AdvancedReports.dsAdvancedRpt.TableQuantityPerMonth2DataTable GetQuantityPerMonthReport(int OrgId,
                                                                                                                    int SelectedOrgId,
                                                                                                                    string DateColumn,
                                                                                                                    DateTime DateStart,
                                                                                                                    DateTime DateEnd)
    {
      Bll.clsOrganization org = new clsOrganization(OrgId);

      using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
      {
        var v = (SelectedOrgId > 0 ?
                    ((bool)org.Data.IsClient ?
                            (from wo in db.TableWorkOrders
                             where (wo.CustomerId == OrgId) &&
                                    (wo.ContractorId == OrgId) &&
                                    ((wo.ActualDelivaryDate != new DateTime(2099, 1, 1)) ||
                                    (wo.ActualDelivaryDate == null)) &&
                                    (wo.Quantity > 0)
                             select wo) :
                            (from wo in db.TableWorkOrders
                             where (wo.ContractorId == OrgId) &&
                                    (wo.CustomerId == OrgId) &&
                                    ((wo.ActualDelivaryDate != new DateTime(2099, 1, 1)) ||
                                    (wo.ActualDelivaryDate == null)) &&
                                    (wo.Quantity > 0)
                             select wo)) :
                    ((bool)org.Data.IsClient ?
                            (from wo in db.TableWorkOrders
                             where (wo.CustomerId == OrgId) &&
                                    ((wo.ActualDelivaryDate != new DateTime(2099, 1, 1)) ||
                                    (wo.ActualDelivaryDate == null)) &&
                                    (wo.Quantity > 0)
                             select wo) :
                            (from wo in db.TableWorkOrders
                             where (wo.ContractorId == OrgId) &&
                                    ((wo.ActualDelivaryDate != new DateTime(2099, 1, 1)) ||
                                    (wo.ActualDelivaryDate == null)) &&
                                    (wo.Quantity > 0)
                             select wo)));
        List<Dal.TableWorkOrder> v2 = null;
        switch (DateColumn)
        {
          case "RequestedDelivaryDate":
            v2 = v.Where(o => (o.RequestedDelivaryDate >= DateStart) && (o.RequestedDelivaryDate <= DateEnd)).ToList();
            break;
          case "PlannedDelivaryDate":
            v2 = v.Where(o => (o.PlannedDelivaryDate >= DateStart) && (o.PlannedDelivaryDate <= DateEnd)).ToList();
            break;
          case "ActualDelivaryDate":
            v2 = v.Where(o => (o.ActualDelivaryDate >= DateStart) && (o.ActualDelivaryDate <= DateEnd)).ToList();
            break;
          default:
            v2 = v.Where(o => (o.SendDate >= DateStart) && (o.SendDate <= DateEnd)).ToList();
            break;
        }

        Reports.AdvancedReports.dsAdvancedRpt.TableQuantityPerMonth2DataTable dt = new MLY.Reports.AdvancedReports.dsAdvancedRpt.TableQuantityPerMonth2DataTable();
        Reports.AdvancedReports.dsAdvancedRpt.TableQuantityPerMonth2Row dr;
        foreach (Dal.TableWorkOrder w in v2)
        {
          DateTime endDate = w.ActualDelivaryDate != null ? (w.ActualDelivaryDate.Value > DateTime.Today ? DateTime.Today : w.ActualDelivaryDate.Value) : DateTime.Today;
          if (w.SendDate.HasValue)
          {
            DateTime d = w.SendDate.Value.AddDays(-w.SendDate.Value.Day + 1);
            while (true)
            {
              DataRow[] drs = dt.Select(string.Format("([ContractorId]={0}) and ([WoMonth]=#{1}#)", w.ContractorId, d.ToString("yyyy-MM-dd")));

              if (drs.Length > 0)
              {
                dr = (Reports.AdvancedReports.dsAdvancedRpt.TableQuantityPerMonth2Row)drs[0];
              }
              else
              {
                dr = dt.NewTableQuantityPerMonth2Row();
                dr.ContractorId = (int)w.ContractorId;
                dr.ContractorName = w.TableOrganization1.OrganizationName;
                dr.WoMonth = d;
                dr.SumOfQuantity = 0;
                dt.Rows.Add(dr);
              }
              dr.SumOfQuantity += w.Quantity.Value;

              d = d.AddMonths(1);
              if (d > endDate)
                break;
            }
          }
        }
        return dt;

        //string strSelect = @" SELECT ContractorId,OrganizationName AS ContractorName ";
        //strSelect += string.Format(@", DATEADD(dd,-(DAY([{0}])-1),[{0}]) AS WoMonth ", DateColumn);
        //strSelect += @",SUM(Quantity) AS SumOfQuantity ";
        //strSelect += @" From TableWorkOrder ";
        //strSelect += @" left join TableOrganizations ";
        //strSelect += @" on TableWorkOrder.ContractorId = TableOrganizations.OrganizationId ";
        //strSelect += string.Format(@" where CustomerId={0} ", OrgId);
        //strSelect += string.Format(@" AND {0} IS NOT NULL AND {0} !='01/01/2099' ", DateColumn);
        //strSelect += string.Format(@" GROUP BY ContractorId,OrganizationName, DATEADD(dd,-(DAY([{0}])-1),[{0}]) ", DateColumn);
        //strSelect += string.Format(@" ORDER BY ContractorId, DATEADD(dd,-(DAY([{0}])-1),[{0}]) ", DateColumn);

        //MLY.Reports.AdvancedReports.dsAdvancedRpt ds = new MLY.Reports.AdvancedReports.dsAdvancedRpt();

        //SqlDataAdapter da = new SqlDataAdapter(strSelect, g.AppConnectionString);
        //da.Fill(ds.TableQuantityPerMonth);
        //return ds.TableQuantityPerMonth;
      }
    }

    public static Reports.AdvancedReports.dsAdvancedRpt.TableDeliveredQuantities2DataTable
                                                        GetInventoryBalanceForReport(int ContractorId,
                                                                                    int CustomerId,
                                                                                    string DateColumn,
                                                                                    DateTime DateStart,
                                                                                    DateTime DateEnd)
    {

      Dictionary<DateTime, decimal> qBase = new Dictionary<DateTime, decimal>();
      Dictionary<DateTime, decimal> qAdded = new Dictionary<DateTime, decimal>();
      Reports.AdvancedReports.dsAdvancedRpt.TableDeliveredQuantities2DataTable dt = null;
      DateTime d = DateStart.Date;
      while (d <= DateEnd.Date)
      {
        qBase[d] = 0;
        qAdded[d] = 0;
        d = d.AddDays(1);
      }

      using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
      {
        // Retrieve all active WO in the period.
        var v = from wo in db.TableWorkOrders
                select wo;
        if (ContractorId == 0)
        {
          v = from wo in db.TableWorkOrders
              where (wo.CustomerId == CustomerId) &&
              ((wo.ActualDelivaryDate != new DateTime(2099, 1, 1)) ||
                                  (wo.ActualDelivaryDate == null) ||
                                  (wo.ActualDelivaryDate >= DateStart)) &&
                                  (wo.Quantity > 0) &&
                                  (wo.SendDate <= DateEnd) &&
                                  (wo.originalWoForDist == null)
              select wo;
        }
        else if (CustomerId == 0)
        {
          v = from wo in db.TableWorkOrders
              where (wo.ContractorId == ContractorId) &&
              ((wo.ActualDelivaryDate != new DateTime(2099, 1, 1)) ||
                                  (wo.ActualDelivaryDate == null) ||
                                  (wo.ActualDelivaryDate >= DateStart)) &&
                                  (wo.Quantity > 0) &&
                                  (wo.SendDate <= DateEnd) &&
                                  (wo.originalWoForDist == null)
              select wo;
        }
        else
        {
          v = from wo in db.TableWorkOrders
              where (wo.CustomerId == CustomerId) &&
               (wo.ContractorId == ContractorId) &&
              ((wo.ActualDelivaryDate != new DateTime(2099, 1, 1)) ||
                                  (wo.ActualDelivaryDate == null) ||
                                  (wo.ActualDelivaryDate >= DateStart)) &&
                                  (wo.Quantity > 0) &&
                                  (wo.SendDate <= DateEnd) &&
                                  (wo.originalWoForDist == null)
              select wo;
        }
        List<Dal.TableWorkOrder> v2 = v.ToList();

        // Scan all WO in the period and calc their balance.
        foreach (Dal.TableWorkOrder wo in v2)
        {
          //decimal totDelivered = 0;

          // Retrieve all distributions of this WO
          List<Dal.TableWorkOrder> dists = (from o in db.TableWorkOrders
                                            where (o.originalWoForDist == wo.WorkOrderId) &&
                                            (o.ActualDelivaryDate != null) &&
                                            (o.Quantity != null)
                                            select o).ToList();
          // Add each delivery to the arrays.
          foreach (Dal.TableWorkOrder dist in dists)
          {
            d = DateStart;
            if (((DateTime)dist.ActualDelivaryDate).Date > d)
              d = ((DateTime)dist.ActualDelivaryDate).Date;
            while (d <= DateEnd)
            {
              qAdded[d] += (decimal)dist.Quantity;

              d = d.AddDays(1);
            }
          }
          // Add (organizationRelation substruct) the WO itself to the arrays
          if (wo.Quantity != null)
          {
            d = DateEnd;
            if (DateColumn == "RequestedDelivaryDate")
            {
              if (wo.RequestedDelivaryDate != null)
                d = ((DateTime)wo.RequestedDelivaryDate).Date;
            }
            else
            {
              if (wo.PlannedDelivaryDate != null)
                d = ((DateTime)wo.PlannedDelivaryDate).Date;
            }
            if (d < DateStart)
              d = DateStart;
            while (d <= DateEnd)
            {
              qBase[d] += (decimal)wo.Quantity;
              qAdded[d] -= (decimal)wo.Quantity;
              d = d.AddDays(1);
            }
          }
        }

        // Build the output datatable.
        dt = new dsAdvancedRpt.TableDeliveredQuantities2DataTable();
        foreach (KeyValuePair<DateTime, decimal> kv in qBase)
        {
          Reports.AdvancedReports.dsAdvancedRpt.TableDeliveredQuantities2Row dr = dt.NewTableDeliveredQuantities2Row();
          dr.DeliveredDate = kv.Key;
          dr.QuantityBase = kv.Value;
          dr.QuantityAdded = qAdded[kv.Key];
          dt.Rows.Add(dr);
        }
      }

      return dt;

      //Reports.AdvancedReports.dsAdvancedRpt.TableQuantityPerMonth2DataTable dt = new MLY.Reports.AdvancedReports.dsAdvancedRpt.TableQuantityPerMonth2DataTable();
      //Reports.AdvancedReports.dsAdvancedRpt.TableQuantityPerMonth2Row dr;
      //    DateTime endDate = w.ActualDelivaryDate != null ? (w.ActualDelivaryDate.Value > DateTime.Today ? DateTime.Today : w.ActualDelivaryDate.Value) : DateTime.Today;
      //    if (w.SendDate.HasValue)
      //    {
      //        DateTime now = w.SendDate.Value.AddDays(-w.SendDate.Value.Day + 1);
      //        while (true)
      //        {
      //            DataRow[] drs = dt.Select(string.Format("([ContractorId]={0}) and ([WoMonth]=#{1}#)", w.ContractorId, now.ToString("yyyy-MM-dd")));

      //            if (drs.Length > 0)
      //            {
      //                dr = (Reports.AdvancedReports.dsAdvancedRpt.TableQuantityPerMonth2Row)drs[0];
      //            }
      //            else
      //            {
      //                dr = dt.NewTableQuantityPerMonth2Row();
      //                dr.ContractorId = (int)w.ContractorId;
      //                dr.ContractorName = w.TableOrganization1.OrganizationName;
      //                dr.WoMonth = now;
      //                dr.SumOfQuantity = 0;
      //                dt.Rows.Add(dr);
      //            }
      //            dr.SumOfQuantity += w.Quantity.Value;

      //            now = now.AddMonths(1);
      //            if (now > endDate)
      //                break;
      //        }
      //    }
      //}
      //return dt;
      //}
    }



    public static dsAdvancedRpt.TableSearchTagRatingDataTable GetContractorsForReport(int OrgId)
    {
      using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
      {
        MLY.Reports.AdvancedReports.dsAdvancedRpt.TableSearchTagRatingDataTable dt = new MLY.Reports.AdvancedReports.dsAdvancedRpt.TableSearchTagRatingDataTable();

        Dal.TableOrganization row = (from org in db.TableOrganizations
                                     where org.OrganizationId == OrgId
                                     select org).FirstOrDefault();
        Dictionary<string, int> ret = new Dictionary<string, int>();


        string[] Tag = (row.Tag).ToString().Split(',');

        for (int i = 0; i < Tag.Length; i++)
        {
          List<Dal.TableOrganization> SearchResult = (from o in db.TableOrganizations
                                                      where o.Tag.Contains(Tag[i])
                                                      select o).ToList();
          DataRow newRow = dt.NewRow();
          newRow["Tag"] = Tag[i];
          newRow["Rating"] = SearchResult.FindIndex(S => S.OrganizationId == row.OrganizationId) + 1;
          dt.Rows.Add(newRow);
        }

        return dt;

      }
    }

    public static int SelfRatingByTag(Dictionary<int, int> Rating, int OrgId)
    {
      return Rating[OrgId];
    }
    public static dsAdvancedRpt.TableSearchTagRatingDataTable SelfRating(int OrgId)
    {
      using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
      {
        MLY.Reports.AdvancedReports.dsAdvancedRpt.TableSearchTagRatingDataTable dt = new MLY.Reports.AdvancedReports.dsAdvancedRpt.TableSearchTagRatingDataTable();

        clsOrganization org = new clsOrganization(OrgId);
        if ((org.IsExist) &&
            (!string.IsNullOrEmpty(org.Data.Tag)))
        {
          string[] tags = org.Data.Tag.Split(',');
          foreach (string s in tags)
          {
            DataRow newRow = dt.NewRow();
            newRow["Tag"] = s;
            newRow["Rating"] = SelfRatingByTag(RateContractorsByTag(s.Trim()), org.Data.OrganizationId);
            dt.Rows.Add(newRow);
          }
        }

        return dt;
      }
    }

    public static Dictionary<int, int> RateContractors(Dictionary<int, int> ContList)
    {
      var v = (from o in ContList
               orderby o.Value descending
               select o);
      int i = 1;
      Dictionary<int, int> ret = new Dictionary<int, int>();
      foreach (KeyValuePair<int, int> kv in v)
      {
        ret.Add(kv.Key, i);
        i++;
      }
      return ret;
    }
    public static Dictionary<int, int> RateContractorsByTag(string TagName)
    {
      using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
      {
        Dictionary<int, int> ConList = new Dictionary<int, int>();

        // Retrieve Contractors.
        List<Dal.TableOrganization> ContractorsList = (from o in db.TableOrganizations
                                                       where o.Tag.Contains(TagName)
                                                       select o).ToList();
        // count relations
        foreach (Dal.TableOrganization Contractor in ContractorsList)
        {
          if (!ConList.Keys.Contains(Contractor.OrganizationId))
          {
            int cnt = db.TableOrganizationRelations.Where(S => S.CustomerId == Contractor.OrganizationId || S.ContractorId == Contractor.OrganizationId).Count();
            ConList.Add(Contractor.OrganizationId, cnt);
          }
        }
        // now rate them

        return RateContractors(ConList);

      }
    }


    public static List<Dal.TableOrganization> GetContractorsByClientId(int clientId)
    {
      using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
      {

        var x = db.TableOrganizationRelations.Where(S => S.CustomerId == clientId).ToList();

        List<Dal.TableOrganization> contractors = (from p in db.TableOrganizationRelations
                                                   join q in db.TableOrganizations
                                                       on
                                                       p.ContractorId equals q.OrganizationId
                                                   where p.CustomerId == clientId
                                                   select q
                ).ToList();

        return contractors;
      }
    }

    public static List<TableOrganization> GetClientsByContractorId(int ContractorId)
    {
      using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
      {

        List<Dal.TableOrganization> contractors = (from p in db.TableOrganizationRelations
                                                   join q in db.TableOrganizations
                                                       on
                                                       p.CustomerId equals q.OrganizationId
                                                   where p.ContractorId == ContractorId
                                                   select q
                ).ToList();

        return contractors;
      }
    }

    
    #endregion

    #region Public Methods
    // ==================================

    public static bool DeleteOrg(int OrgId)
    {
      using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
      {
        //check if organization has relations
        var RelationsList = (from p in db.TableOrganizationRelations
                             where ((p.ContractorId == OrgId) || (p.CustomerId == OrgId))
                             select p
                ).ToList();
        if (RelationsList.Count > 0) return false;
        //check if organization has Work orders
        var WoList = (from p in db.TableWorkOrders
                      where ((p.ContractorId == OrgId) || (p.CustomerId == OrgId))
                      select p
                ).ToList();
        if (WoList.Count > 0) return false;

        //if organization has neither of these - it can be deleted
        Dal.TableOrganization row =
        (from orgDetails in db.TableOrganizations
         where orgDetails.OrganizationId == OrgId
         select orgDetails).FirstOrDefault();

        db.TableOrganizations.DeleteOnSubmit(row);
        db.SubmitChanges();
        return true;
      }

    }

    public static TableOrganization GetOrganizationById(int OrgId)
    {
        using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
        {
            return (from o in db.TableOrganizations
                    where o.OrganizationId == OrgId
                    select o).FirstOrDefault();
        }
    }

    public static List<Dal.TableOrganization> GetOrgByNameAndClassification(int ClassificationId, string OrgName)
    {
      using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
      {
        return (from o in db.TableOrganizations
                join p in db.TableOrganizationClassifications on o.OrganizationId equals p.OrganizationId
                where o.OrganizationName.Contains(OrgName) &&
                ((p.ClassificationId == ClassificationId) || (ClassificationId == 0))
                select o).ToList<Dal.TableOrganization>();
      }
    }

    public static string GetOrgNameById(int OrgId)
    { 
        string OrgName = "";
        using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
        {
            OrgName = (from o in db.TableOrganizations
                       where o.OrganizationId == OrgId
                       select o.OrganizationName).FirstOrDefault();
        }
        return OrgName;
    }

    public static bool IsClient(int OrgId)
    {
        bool IsCl = false;
        using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
        {
            IsCl = (from o in db.TableOrganizations
                    where o.OrganizationId == OrgId
                    select o.IsClient.HasValue ? o.IsClient.Value : false).FirstOrDefault();
        }
        return IsCl;
    }

    public static bool CanBeClient(int OrgId)
    {
        bool CanBeClient = false;

        using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
        {
            CanBeClient = (from o in db.TableOrganizations
                           where o.OrganizationId == OrgId
                           select o.IsClient.HasValue ? o.IsClient.Value : false).FirstOrDefault();
        }
        return CanBeClient;
    }

    public static bool CanBeContructor(int OrgId)
    {
        bool CanBeContructor = false;
        using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
        {
            CanBeContructor = (from o in db.TableOrganizations
                               where o.OrganizationId == OrgId
                               select o.IsContractor.HasValue ? o.IsContractor.Value : false).FirstOrDefault();
        }
        return CanBeContructor;
    }

    public void Save()
    {
      if (IsExist)
      {
        _DataRow.UpdateDate = DateTime.Now;
        _DataRow.UpdateBy = clsUser.CurrentUserId;
        _db.SubmitChanges();
      }
      else
      {
        _DataRow.DateCreated = DateTime.Now;
        _DataRow.UpdateDate = DateTime.Now;
        _DataRow.UpdateBy = clsUser.CurrentUserId;

        _db.TableOrganizations.InsertOnSubmit(_DataRow);
        _db.SubmitChanges();
      }
    }
    // ==================================
    #endregion

    #region Public Properties
    // ==================================
    public Dal.TableOrganization Data
    {
      get { return _DataRow; }
    }
    // ==================================
    #endregion

    #region Fields
    // ==================================
    public bool IsExist = false;
    Dal.lqKbmDataContext _db = null;
    Dal.TableOrganization _DataRow = null;
    // ==================================
    #endregion
  }
}